<template>
  <div class="searchBox">
    <input type="text" placeholder="请输入城市名称" class="search_ipt" v-model="keyword">
    <div class="search_content" ref="search"  v-show="keyword">
      <ul>
        <li v-for="(item,index) in list" :key="index" @click="handleChoseCity(item.name)" class="border-bottom">{{item.name}}</li>
        <li v-show="hasNoData">暂无数据</li>
      </ul>
    </div>
 
  </div>
</template>

<script>
import Bscroll from "better-scroll";
import { mapMutations } from "vuex";
export default {
  name: "search",
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: "",
      list: []
    };
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    }
  },
  mounted() {
    // 通过ref获取dom
    this.scroll = new Bscroll(this.$refs.search);
  },
  watch: {
    keyword() {
      if (!this.keyword) {
        this.list = [];
        return;
      }
      const result = [];
      for (let i in this.cities) {
        this.cities[i].forEach(value => {
          if (
            value.spell.indexOf(this.keyword) > -1 ||
            value.name.indexOf(this.keyword) > -1
          ) {
            result.push(value);
          }
        });
      }
      this.list = result;
    }
  },
  methods: {
    handleChoseCity(city) {
      this.changeCity(city);
      this.$router.push("/");
    },
    ...mapMutations(["changeCity"])
  }
};
</script>

<style lang="stylus" scoped>
$bgColor = #00bcd4;

.searchBox {
  background: $bgColor;
  padding: 0.2rem;
}

.search_ipt {
  width: 100%;
  background: #fff;
  line-height: 0.6rem;
  border-radius: 4px;
  padding: 0 0.1rem;
  box-sizing: border-box;
}

.search_content {
  z-index: 9;
  overflow: hidden;
  position: absolute;
  top: 1.98rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;

  li {
    line-height: 0.6rem;
    padding: 0 0.1rem;
    box-sizing: border-box;
  }
}

.search-item {
  line-height: 0.62rem;
  padding-left: 0.2rem;
  background: #fff;
  color: #666;
}
</style>